package com.yami.shop.api.controller;

import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.service.AttachFileService;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 文件上传 controller
 * @author lgh
 *
 */
@RestController
@RequestMapping("/p/file")
public class FileController {
	
	@Autowired
	private AttachFileService attachFileService;
	@Autowired
	private Qiniu qiniu;

	@Autowired
	WxCpService wxCpService;
	
	@PostMapping("/upload/element")
	public ResponseEntity<String> uploadElementFile(@RequestParam("file") MultipartFile file) throws Exception{
		if(file.isEmpty()){
            return ResponseEntity.noContent().build();
        }
		// 上传到七牛云
		// String fileName = attachFileService.uploadFile(file.getBytes(),file.getOriginalFilename());

		// 上传图片到微信后台
		// String imgUrl = wxCpService.getMediaService().uploadImg(multipartFileToFile(file));
		// 上传临时素材  发送卡片用到
		File toFile=multipartFileToFile(file);
		WxMediaUploadResult image = wxCpService.getMediaService().upload("image", toFile);
		toFile.delete();
		return ResponseEntity.ok(image.getMediaId());
	}
	
	@PostMapping("/upload/tinymceEditor")
	public ResponseEntity<String> uploadTinymceEditorImages(@RequestParam("editorFile") MultipartFile editorFile) throws IOException{
		String fileName =  attachFileService.uploadFile(editorFile.getBytes(),editorFile.getOriginalFilename());
        return ResponseEntity.ok(qiniu.getResourcesUrl() + fileName);
	}

	public File multipartFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if (file.equals("") || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}
	public  void inputStreamToFile(InputStream ins,File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
